package com.jm.call;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gyf.barlibrary.ImmersionBar;
import com.jm.chat.R;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import cn.jiguang.jmrtc.api.JMRtcClient;
import cn.jiguang.jmrtc.api.JMRtcSession;
import cn.jiguang.jmrtc.api.JMSignalingMessage;
import cn.jpush.im.android.api.callback.RequestCallback;
import cn.jpush.im.android.api.model.UserInfo;

public class CallActivity extends AppCompatActivity implements View.OnClickListener,JMRtcClientManager.JMRctCallback {

    protected ImageView ivLogo;
    protected TextView tvCallState;//通话状态
    protected TextView tvCallReject,tvCallAccept;//拒绝通话，接听通话
    protected TextView tvCallHangUp;//挂断通话
    protected ImageView ivSpeaker;//扬声器按钮
    private String mCategoryCall;//通话类型，received接听
    private String mVideoCall;//视频通话
    private String mChatId;//聊天id
    TextView btnSwitchCamera;

    private LinearLayout llRemoteSurface,llLocalSurface;
    private RelativeLayout clHandUp;//视频挂断UI
    private ImageView ivHandUp;//视频挂断按钮
    private TextView tvCallTimeLong;//通话时长
    private Handler mHandler = new Handler();
    private long mCallTimeLong;//通话时长
    private SurfaceView mLocalSurfaceView,mRemoteSurfaceView;
    private boolean isChangeSurface = false;
    private int mRoleType;//1发起方，2接受方
    private long mEndTime;//课程结束时间

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        mCategoryCall = intent.getStringExtra(JMRtcClientManager.CALL_CATEGORY);
        mChatId = intent.getStringExtra("ChatId");
        mVideoCall = intent.getStringExtra(JMRtcClientManager.CALL_VIDEO);
        if("video".equals(mVideoCall)){
            setContentView(R.layout.activity_call_video);
            ImmersionBar.with(this).statusBarColor(R.color.transparent).statusBarDarkFont(true).init();
        }else{
            setContentView(R.layout.activity_call);
        }

        initView();
        initListener();
        getSession();

        SoundManage.getInstance().playSound(this, "ring.wav");
    }

    private void initView() {
        ivLogo = findViewById(R.id.iv_logo);
        tvCallState = findViewById(R.id.tv_call_state);
        tvCallReject = findViewById(R.id.tv_call_reject);
        tvCallAccept = findViewById(R.id.tv_call_accept);

        if("video".equals(mVideoCall)){
            llRemoteSurface = findViewById(R.id.ll_romote);
            llLocalSurface = findViewById(R.id.ll_local);
            btnSwitchCamera = findViewById(R.id.btn_switch_camara);
            clHandUp = findViewById(R.id.cl_handup);
//            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) clHandUp.getLayoutParams();
//            params.height = ScreenUtil.getDisplayHeight() - ScreenUtil.getStatusBarHeight(this)-(ScreenUtil.getDisplayHeight() - ScreenUtil.getStatusBarHeight(this))/2;
            RelativeLayout.LayoutParams paramsLocal = (RelativeLayout.LayoutParams) llLocalSurface.getLayoutParams();
            paramsLocal.width = DisplayUtil.getDensityWdith(this)*DisplayUtil.dip2px(this,120)/DisplayUtil.getDensityHeight(this);

            ivHandUp = findViewById(R.id.iv_handup);
            tvCallTimeLong = findViewById(R.id.tv_call_time_long);
            JMRtcClientManager.getJMRtcClientManager().setJMRctCallback(this);
        }else{
            tvCallHangUp = findViewById(R.id.tv_call_hangup);
            ivSpeaker = findViewById(R.id.iv_speaker);
        }

        if(JMRtcClientManager.CALL_RECEIVE.equals(mCategoryCall)){
            setReceiveCallVisible(true);
            setCallState(3);
        }else{
            setReceiveCallVisible(false);

            JMSignalingMessage.MediaType mediaType = JMSignalingMessage.MediaType.AUDIO;//默认语音
            if("video".equals(mVideoCall)){//视频
                mediaType = JMSignalingMessage.MediaType.VIDEO;
            }
            if(!JMRtcClientManager.CALL_RECEIVE.equals(mCategoryCall)){
                JMRtcClientManager.getJMRtcClientManager().startCall(mChatId,mediaType);
            }
        }
    }

    /**
     * 获取当前通话session对象。
     */
    private void getSession(){
        JMRtcSession callSession = JMRtcClient.getInstance().getSession();
        if(callSession!=null){
            callSession.getInviterUserInfo(new RequestCallback<UserInfo>(){
                @Override
                public void gotResult(int i, String s, UserInfo userInfo) {
                    Log.e("Log","==="+s);
                }
            });
        }
    }

    private void setReceiveCallVisible(boolean isVisible){
        if(isVisible){
            tvCallReject.setVisibility(View.VISIBLE);
            tvCallAccept.setVisibility(View.VISIBLE);
            if("video".equals(mVideoCall)) {//
                clHandUp.setVisibility(View.GONE);
            }else{
                tvCallHangUp.setVisibility(View.GONE);
                ivSpeaker.setVisibility(View.GONE);
            }
        }else{
            tvCallReject.setVisibility(View.GONE);
            tvCallAccept.setVisibility(View.GONE);
            if("video".equals(mVideoCall)) {//
                clHandUp.setVisibility(View.VISIBLE);
            }else{
                tvCallHangUp.setVisibility(View.VISIBLE);
                ivSpeaker.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initListener(){
        tvCallReject.setOnClickListener(this);
        tvCallAccept.setOnClickListener(this);
        btnSwitchCamera.setOnClickListener(this);

        if("video".equals(mVideoCall)) {//视频
            ivHandUp.setOnClickListener(this);
        }else{
            tvCallHangUp.setOnClickListener(this);
            ivSpeaker.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.tv_call_reject){//拒接
            JMRtcClientManager.getJMRtcClientManager().refuseCall();
        }else if(v.getId()==R.id.tv_call_accept){//接听
            JMRtcClientManager.getJMRtcClientManager().acceptCall();
        }else if(v.getId()==R.id.tv_call_hangup || v.getId()==R.id.iv_handup){//挂断
            JMRtcClientManager.getJMRtcClientManager().hangUp();
        }else if(v.getId()==R.id.iv_speaker){//扬声器
            ivSpeaker.setSelected(!ivSpeaker.isSelected());
            JMRtcClient.getInstance().enableSpeakerphone(ivSpeaker.isSelected());
        }else if(v.getId()==R.id.btn_switch_camara){
            JMRtcClient.getInstance().switchCamera();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCallEvent(CallEventBean event) {
        if(event.event==CallEventBean.EVENT_START_CALL){//发起语音通话事件,等待对方应答
            setCallState(1);
        }else if(event.event==CallEventBean.EVENT_ACCEPT_CALL_SUCCESS){//接听电话事件
            setReceiveCallVisible(false);
        }else if(event.event==CallEventBean.EVENT_REFUSE_CALL_SUCCESS){//拒听电话事件
            finish();
        }else if(event.event==CallEventBean.EVENT_HANGUP_CALL_SUCCESS){//挂断电话事件
            finish();
        }else if(event.event==CallEventBean.EVENT_ENGINE_INIT_COMPLETE){//音视频引擎初始化完成事件

        }else if(event.event==CallEventBean.EVENT_ON_CALL_OUTGOING){//通话已播出事件

        }else if(event.event==CallEventBean.EVENT_ON_CALL_INVITE_RECEIVED){//收到通话邀请事件
            setReceiveCallVisible(true);
            setCallState(3);
        }else if(event.event==CallEventBean.EVENT_ON_CALL_CONNECTED){//通话连接已建立
            setReceiveCallVisible(false);
            setCallState(2);
            if("video".equals(mVideoCall)) {//视频
                JMRtcClient.getInstance().enableSpeakerphone(true);
                mCallTimeLong = 0;
                timing();
            }
        }else if(event.event==CallEventBean.EVENT_ON_CALL_ERROR){//本地通话连接断开,通话发生错误R
            if(event.responseCode==-1){
                JMRtcClientManager.getJMRtcClientManager().hangUp();
            }
            finish();
        }
    }

    private void timing(){
        mHandler.postDelayed(mRunnable,1000);
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mCallTimeLong++;
            StringBuilder timeLongBuilder = new StringBuilder();
            long result = mCallTimeLong/(60*60);
            if(result<10){
                timeLongBuilder.append("0"+result);
            }else{
                timeLongBuilder.append(result);
            }
            timeLongBuilder.append(":");
            result = mCallTimeLong%(60*60);
            result = result/60;
            if(result<10){
                timeLongBuilder.append("0"+result);
            }else{
                timeLongBuilder.append(result);
            }
            timeLongBuilder.append(":");
            result = mCallTimeLong%60;
            if(result<10){
                timeLongBuilder.append("0"+result);
            }else{
                timeLongBuilder.append(result);
            }
            tvCallTimeLong.setText(timeLongBuilder.toString());
            mHandler.postDelayed(mRunnable,1000);
            if(mRoleType == 1) {//发起
                long endtime = mEndTime-System.currentTimeMillis();
                if(endtime<=0){
                    JMRtcClientManager.getJMRtcClientManager().hangUp();
                }
            }
        }
    };

    private void setCallState(int state){
        if(1==state){
            mRoleType = 1;
            tvCallState.setText("等待对方应答...");
            ivLogo.setVisibility(View.VISIBLE);
        }else if(2==state){
            if("video".equals(mVideoCall)){//视频
                tvCallState.setText("");
                ivLogo.setVisibility(View.GONE);
            }else{//音频
                tvCallState.setText("通话中...");
                ivLogo.setVisibility(View.VISIBLE);
            }
            SoundManage.getInstance().stop();
        }else if(3==state){
            mRoleType = 2;
            tvCallState.setText("待接听...");
            ivLogo.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mRunnable != null){
            mHandler.removeCallbacks(mRunnable);
        }
        SoundManage.getInstance().stop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onCallConnected(JMRtcSession callSession,final SurfaceView localSurfaceView) {
        Log.e("Log","======onCallConnected="+mRoleType);
        if("video".equals(mVideoCall)){//视频
            // mLocalSurfaceView = localSurfaceView;
            if(mRoleType == 2){//接受
                llLocalSurface.addView(localSurfaceView);
            }else if(mRoleType == 1){//发起
                llLocalSurface.addView(localSurfaceView);
            }
//            changeSurfaceView();
        }
    }

    @Override
    public void onCallMemberJoin(UserInfo joinedUserInfo, SurfaceView remoteSurfaceView) {
        Log.e("Log","======onCallMemberJoin="+mRoleType);
        if("video".equals(mVideoCall)){//视频
//            mRemoteSurfaceView = remoteSurfaceView;
            if(mRoleType == 2){//接受
                llRemoteSurface.addView(remoteSurfaceView);
            }else if(mRoleType == 1){//发起
                llRemoteSurface.addView(remoteSurfaceView);
            }
//            changeSurfaceView();
        }
    }

    private void changeSurfaceView(){
        if(mLocalSurfaceView!=null && mRemoteSurfaceView!=null){
//            llLocalSurface.removeAllViews();
//            llRemoteSurface.removeAllViews();
//            if(isChangeSurface){
                llLocalSurface.addView(mLocalSurfaceView);
                llRemoteSurface.addView(mRemoteSurfaceView);
//            }else{
//                llLocalSurface.addView(mRemoteSurfaceView);
//                llRemoteSurface.addView(mLocalSurfaceView);
//            }
        }
    }

}
